package com.example.leetdemo.finash;

import java.util.Stack;

public class Solution856 {

    public int scoreOfParentheses(String s) {
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push("(");
            } else {
                int n = 0;
                while (true) {
                    String str = stack.pop();
                    if (str.equals("(")) {
                        if (n == 0) {
                            n = 1;
                        } else {
                            n = n * 2;
                        }
                        stack.push(n + "");
                        break;
                    } else {
                        n = n + Integer.parseInt(str);
                    }
                }
            }
        }
        int score = 0;
        while (stack.size() > 0) {
            score += Integer.parseInt(stack.pop());
        }
        return score;
    }
}
